package com.dongxingx.renchuang.tablet

import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.dongxingx.renchuang.tablet.utils.GPIOHelper
import com.dongxingx.renchuang.tablet.utils.NFCHelper
import com.dongxingx.renchuang.tablet.utils.StringHelper
import kotlinx.android.synthetic.main.layout_control.*
import kotlinx.android.synthetic.main.layout_nfc.*
import java.util.*
import kotlin.concurrent.timer


class MainActivity : AppCompatActivity() {

    private var isOpenRfid = false
        set(value) {
            field = value
            buttonRc522Action.text = if(value) "停止读卡" else "启动读卡"
            if (value) {
                NFCHelper.openZHRFID()
            } else {
                NFCHelper.closeZHRFID()
            }
        }
    private var isWriteRfid = false
        set(value) {
            field = value
            buttonRc522Write.text = if(value) "停止写入" else "写块"
            if (value) {
                val blockStr = etBlock.text.toString()
                NFCHelper.writeBlock(blockStr)
            } else {
                NFCHelper.stopWrite()
            }
        }
    private val handler = Handler()
    private var running = false
    private var isRelayOn = false
        set(value) {
            field = value
            if (value) {
                GPIOHelper.relayOn()
            } else {
                GPIOHelper.relayOff()
            }
            buttonRelay.text = "${if(value) "关" else "开"}继电器"
        }
    private var isLedOn = false
        set(value) {
            field = value
            if (value) {
                GPIOHelper.lightingOn()
            } else {
                GPIOHelper.lightingOff()
            }
            buttonLed.text = "${if(value) "关" else "开"}补光灯"
        }
    private var isAutoTest = false
        set(value) {
            field = value
            buttonAutoTest.text = "${if(value) "关闭" else "开启"}自动切换"
        }
    private var autoTimer: Timer? = null
    private var isEnableSector = false
        set(value) {
            field = value
            buttonRc522EnableSector.text = "${if(value) "关闭" else "开启"}读扇区"
        }
    private var isEnableContinuity = false
        set(value) {
            field = value
            buttonRc522EnableContinuity.text = "${if(value) "关闭" else "开启"}连续读卡"
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        buttonRc522Action.setOnClickListener {
            isWriteRfid = false
            isOpenRfid = !isOpenRfid
        }
        val shopIdAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, (1..15).map { it.toString() })
        shopIdAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerSector.adapter = shopIdAdapter
        spinnerSector.setSelection(NFCHelper.readSector-1)

        val blockAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, (0..2).map { it.toString() })
        blockAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerBlock.adapter = blockAdapter
        spinnerBlock.setSelection((NFCHelper.readBlock%4))

        etPassword.setText(NFCHelper.sectorPwd)
        buttonRc522Save.setOnClickListener {
            if(etPassword.text.length != 12) {
                Toast.makeText(this, "请填写正确的密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            NFCHelper.setup(etPassword.text.toString(),
                spinnerSector.selectedItem.toString(),
                ((spinnerSector.selectedItemPosition+1)*4 + spinnerBlock.selectedItemPosition).toString()
            )
        }
        buttonRelay.setOnClickListener {
            isRelayOn = !isRelayOn
        }
        buttonLed.setOnClickListener {
            isLedOn = !isLedOn
        }
        buttonAutoTest.setOnClickListener {
            isAutoTest = !isAutoTest
            autoTimer?.cancel()
            isRelayOn = isAutoTest
            isLedOn = isAutoTest
            buttonRelay.isEnabled = !isAutoTest
            buttonLed.isEnabled = !isAutoTest
            if (isAutoTest) {
                autoTimer = timer(period = 1000) {
                    handler.post {
                        isRelayOn = !isRelayOn
                        isLedOn = !isLedOn
                    }
                }
            }
        }
        buttonRc522Write.setOnClickListener {
            val blockStr = etBlock.text.toString()
            if (blockStr.length != 32) {
                NFCHelper.listener?.onWriteBlockFail("请输入16位内容")
                return@setOnClickListener
            }
            isOpenRfid = false
            isWriteRfid = !isWriteRfid
        }
        buttonRc522EnableSector.setOnClickListener {
            isEnableSector = !isEnableSector
            if (isEnableSector) {
                NFCHelper.rfidCrl.Sector_read_enable()
            } else {
                NFCHelper.rfidCrl.Sector_read_disable()
            }
        }
        buttonRc522EnableContinuity.setOnClickListener {
            isEnableContinuity = !isEnableContinuity
            if (isEnableSector) {
                NFCHelper.rfidCrl.read_continuity_enable()
            } else {
                NFCHelper.rfidCrl.read_continuity_disable()
            }
        }
        NFCHelper.listener = object : NFCHelper.NFCListener {
            override fun onNFCReadSuccess(cardNo10D: String, blockContent: String?) {
                tvCardNo.text = cardNo10D
                tvSectorContent.text = blockContent
            }

            override fun onWriteBlockFail(msg: String) {
                isWriteRfid = false
                Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
            }

            override fun onWriteBlockSuccess() {
                isWriteRfid = false
                Toast.makeText(this@MainActivity, "写入成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        NFCHelper.closeZHRFID()
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menu.add(1, 1, 1, "退出")
        return true
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            1 -> finish()
        }
        return super.onOptionsItemSelected(item)
    }
}